'use strict'
const https = require('https')

exports.main = async (event, context) => {
  let body = event
  if (event.body) {
    body = JSON.parse(event.body)
  }

  const { filePath } = body

  if (!filePath || !filePath.startsWith('https://')) {
    return {
      success: false,
      message: '无效的文件路径'
    }
  }

  try {
    const content = await new Promise((resolve, reject) => {
      https.get(filePath, (res) => {
        let data = ''

        res.on('data', chunk => {
          data += chunk
        })

        res.on('end', () => {
          resolve(data)
        })

      }).on('error', (err) => {
        reject(err)
      })
    })

    return {
      success: true,
      content
    }

  } catch (err) {
    console.error('读取远程文件失败:', err)
    return {
      success: false,
      message: '读取失败',
      error: err.message
    }
  }
}
